package com.xuetang9.fujian.threaddemo;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author: fujian
 * @description: 线程池的使用
 * @date: 2021/5/9 8:43
 * @version: V1.0
 * @package: com.xuetang9.fujian.threaddemo
 **/
@SuppressWarnings("all")
public class ThreadPoolDemo {

    public static void main(String[] args) {
        String content = "我们要有坚持不懈的精神";
        // 创建固定活动线程的线程池对象
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            // 实例化任务
            ThreadPoolTask task = new ThreadPoolTask(content);
            //让线程去执行这个任务
            threadPool.execute(task);
        }
    }
    static class ThreadPoolTask implements Runnable{
        private String content;

        public ThreadPoolTask(String content) {
            this.content = content;
        }

        @Override
        public void run() {
            for (int i = 0; i < content.length(); i++) {
                System.out.println(Thread.currentThread().getName() + "正在打印：" + content.charAt(i));
                try {
                    TimeUnit.MILLISECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
